import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import { ErrorCode } from '../constants/error-code.enum';
import { ErrorMessage } from '../constants/error-message.enum';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let code = ErrorCode.INTERNAL_ERROR;
    let message = ErrorMessage[ErrorCode.INTERNAL_ERROR];

    if (exception instanceof HttpException) {
      status = exception.getStatus();
      const exceptionResponse = exception.getResponse();

      // 处理自定义异常
      if (
        typeof exceptionResponse === 'object' &&
        'code' in exceptionResponse
      ) {
        code = (exceptionResponse as any).code;
        message = ErrorMessage[code] || (exceptionResponse as any).message;
      } else {
        // 处理内置异常
        switch (status) {
          case HttpStatus.BAD_REQUEST:
            code = ErrorCode.PARAM_ERROR;
            message = ErrorMessage[ErrorCode.PARAM_ERROR];
            break;
          case HttpStatus.UNAUTHORIZED:
            code = ErrorCode.UNAUTHORIZED;
            message = ErrorMessage[ErrorCode.UNAUTHORIZED];
            break;
          case HttpStatus.FORBIDDEN:
            code = ErrorCode.FORBIDDEN;
            message = ErrorMessage[ErrorCode.FORBIDDEN];
            break;
          case HttpStatus.NOT_FOUND:
            code = ErrorCode.NOT_FOUND;
            message = ErrorMessage[ErrorCode.NOT_FOUND];
            break;
          default:
            code = ErrorCode.INTERNAL_ERROR;
            message = ErrorMessage[ErrorCode.INTERNAL_ERROR];
        }
      }
    }

    response.status(status).json({
      code,
      message,
      timestamp: new Date().toISOString(),
      path: ctx.getRequest().url,
    });
  }
}
